﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MessageBusConn;
using System.Runtime.InteropServices;

namespace Common
{
    public class BusHelper
    {
        public static List<tbcontrol> List=new List<tbcontrol>();

        [DllImport("User32.dll", EntryPoint = "FindWindow")]
        private static extern int FindWindow(string lpClassName, string lpWindowName);
        public static void Bind()
        {
            List = tbcontrol.Fetch("");

            foreach (var tb in List)
            {
                var path = @".\private$\" + tb.BusCode;
                var mq = CreateMessageQueue(path);
                mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                var bus=new Bus(mq, tb.Url);
                Thread thread = new Thread(bus.Receiver);
                thread.Start();
            }
        }

        public static MessageQueue GetInstance(string code)
        {
            if (List.Any(n => n.BusCode == code))
            {
                var path = @".\private$\" + code;
                var mq = CreateMessageQueue(path);
                mq.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                return mq;
            }
            return null;

        }
        public static MessageQueue CreateMessageQueue(string path)
        {
            MessageQueue mq = null;

            if (MessageQueue.Exists(path))
            {
                mq = new MessageQueue(path);
            }
            else
            {
                mq = MessageQueue.Create(path, true);
            }

            return mq;
        }
     
    }

    public class Bus
    {
        private string _url = null;
        protected MessageQueue _msmq = null;

        public Bus(MessageQueue msmq, string url)
        {
            _msmq = msmq;
            _url = url;
        }
        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);

       

        public virtual void Receiver()
        {
            while (true)
            {
                try
                {
                    Message m = _msmq.Receive(MessageQueueTransactionType.Single);
                    HttpHelper.Http(_url, "post", "", null, m?.Body?.ToString());
                }
                catch (Exception ex)
                {

                }
            }
        }
    }
}
